import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;


public class TCPPortScannerThread extends Thread {
	int startPort; 				// Target starting port range
	int endPort;				// Target ending port range
	InetAddress hostAddress;	// Target IP address
	
	/**
	 * Constructor of the class TCPPortScannerThread. Initializes class variables.
	 * @param hostAddress
	 * 		The target IP address
	 * @param startPort
	 * 		Target starting port of the range
	 * @param endPort
	 * 		Target ending port of the range
	 */
	public TCPPortScannerThread(InetAddress hostAddress, int startPort, int endPort) {
		this.hostAddress = hostAddress;
		this.startPort = startPort;
		this.endPort = endPort;
	}
	
	/**
	 * Method that runs the TCP port discovery on the specified range [startPort, endPort].
	 * For each port, it creates a new Socket for the specifed hostAddress and port.
	 * If there is an IOException, the port is closed, otherwise the port is open.
	 */
	public void run() {
		for(int i = startPort; i <= endPort; i++) {
			//System.out.println("Scanning port "+port);
			try {
				Socket socket = new Socket(hostAddress, i);
				socket.close();

				OpenPorts.getInstance().set(i, true);
				//System.out.println("\tPort "+port+" is open");
			} 
			catch(IOException e) {
				OpenPorts.getInstance().set(i, false);
				//System.out.println("\tPort "+port+" isn't open");
			}
		}
	}
}
